package common

import (
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
	"time"
)

func GenerateJwt(username string) string {
	claims := jwt.MapClaims{
		USERNAME: username,
		EXP:      time.Now().Add(time.Hour * 72).Unix(),
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenStr, _ := token.SignedString([]byte(Config.Auth.JwtKey))
	return tokenStr
}

func ValidateToken(tokenString string) (*jwt.Token, error) {
	// 解析 JWT
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// 验证签名算法是否正确
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}

		// 设置密钥
		return []byte(Config.Auth.JwtKey), nil
	})

	if err != nil {
		return nil, err
	}

	// 检查是否已过期
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		expirationTime := claims[EXP].(float64)
		if time.Now().Unix() > int64(expirationTime) {
			return nil, fmt.Errorf("token has expired")
		}
		return token, nil
	}

	return nil, fmt.Errorf("invalid token")
}

func HashPassword(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return "", err
	}
	return string(bytes), nil
}

func CheckPasswordHash(password, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	if err != nil {
		return false
	}
	return true
}

func NewUUID() string {
	uuid6, err := uuid.NewV6()
	if err != nil {
		Logger.Infof("new uuid error")
		panic(err)
	}
	return uuid6.String()
}
